/*
 * Copyright 2009 Google Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */
package org.starsource.forum.client.view;

import java.util.ArrayList;
import java.util.List;

import org.starsource.forum.client.StarForum;
import org.starsource.forum.client.StarForum.AppWindow;
import org.starsource.forum.client.domain.ResourceObject;
import org.starsource.forum.client.domain.SessionObject;
import org.starsource.forum.client.handler.SessionUpdateHandler;
import org.starsource.forum.client.util.ImageFilter;
import org.starsource.forum.client.web.ForumService;
import org.starsource.forum.client.web.ForumServiceAsync;
import com.google.gwt.core.client.GWT;
import com.google.gwt.dom.client.Style.Visibility;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.KeyCodes;
import com.google.gwt.event.dom.client.KeyPressEvent;
import com.google.gwt.event.dom.client.KeyPressHandler;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.uibinder.client.UiHandler;
import com.google.gwt.uibinder.client.UiTemplate;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Anchor;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.DecoratedPopupPanel;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.Widget;

/**
 * A simple widget representing prev/next page navigation.
 */
class SessionDetailToolbar extends Composite {
	private final ForumServiceAsync forumService = GWT.create(ForumService.class);

	@UiTemplate("SessionDetailToolbar.ui.xml")
  interface Binder extends UiBinder<Widget, SessionDetailToolbar> { }
  private static final Binder binder = GWT.create(Binder.class);

  @UiField Anchor followButton;
  @UiField Anchor browseButton;
  @UiField Anchor editButton;
  @UiField Anchor deleteButton;

  private SessionObject sessionObject;
  public void setSessionObject(SessionObject sessionObject) {
	  this.sessionObject = sessionObject;
	  if (sessionObject == null) {
		  this.setVisibility(followButton, false);
		  this.setVisibility(browseButton, false);
		  this.setVisibility(editButton, false);
		  this.setVisibility(deleteButton, false);
	  } else if (sessionObject.getOwner().getId() == StarForum.getUserObject().getId()) {
		  this.setVisibility(followButton, true);
		  this.setVisibility(browseButton, true);
		  this.setVisibility(editButton, true);
		  this.setVisibility(deleteButton, true);
	  } else {
		  this.setVisibility(followButton, true);
		  this.setVisibility(browseButton, true);
		  this.setVisibility(editButton, false);
		  this.setVisibility(deleteButton, false);
	  }
  }
  private SessionUpdateHandler sessionUpdateHandler;
  public void setSessionUpdateHandler(SessionUpdateHandler sessionUpdateHandler) {
	  this.sessionUpdateHandler = sessionUpdateHandler;
  }

  public SessionDetailToolbar() {
    initWidget(binder.createAndBindUi(this));
  }

  public void update() {
//    setVisibility(newerButton, startIndex != 0);
//    setVisibility(olderButton,
//        startIndex + SessionList.VISIBLE_EMAIL_COUNT < count);
//    countLabel.setInnerText("" + (startIndex + 1) + " - " + max + " of "
//        + count);
  }

  @UiHandler("followButton")
  void onFollowButtonClicked(ClickEvent event) {
	  SessionFollowDialog sessionFollowDialog = new SessionFollowDialog();
	  sessionFollowDialog.setSessionObject(sessionObject);
	  sessionFollowDialog.setSessionUpdateHandler(sessionUpdateHandler);
	  sessionFollowDialog.center();
  }

  @UiHandler("browseButton")
  void onBrowseButtonClicked(ClickEvent event) {
	  List<ResourceObject> resources = new ArrayList<ResourceObject>();
	  for(int index = 0; index < sessionObject.getMessages().size(); index ++) {
		  resources.addAll(sessionObject.getMessages().get(index).getResources());
	  }
		ImageFilter imageFilter = new ImageFilter();
		ImageBrowser imageBrowser = StarForum.getInstance().getImageBrowser();
		imageBrowser.setImageList(imageFilter.getSatisfied(resources));

		StarForum.getInstance().switchWindow(AppWindow.IMAGE_BROWSER);
  }

  @UiHandler("editButton")
  void onEditClicked(ClickEvent event) {
	    // Create a basic popup widget
	    final DecoratedPopupPanel simplePopup = new DecoratedPopupPanel(true);
		  final TextBox title = new TextBox();
		  title.setWidth("480px");
		  title.setText(sessionObject.getTitle());

		  title.addKeyPressHandler(new KeyPressHandler() {

			@Override
			public void onKeyPress(KeyPressEvent event) {
				if (event.getCharCode() == KeyCodes.KEY_ESCAPE) {
					simplePopup.hide();
				} else if (event.getCharCode() == KeyCodes.KEY_ENTER) {
					forumService.updateTitle(title.getText(),sessionObject.getId(), new AsyncCallback<Void>() {

						@Override
						public void onFailure(Throwable caught) {
							// TODO Auto-generated method stub

						}

						@Override
						public void onSuccess(Void result) {
							simplePopup.hide();
							sessionUpdateHandler.onSessionUpdate(sessionObject);
						}

					});
				}
			}

		  });

		  simplePopup.ensureDebugId("cwBasicPopup-simplePopup");
	    simplePopup.setWidth("500px");
	    simplePopup.setWidget(title);

        // Reposition the popup relative to the button
        Widget source = (Widget) event.getSource();
        int left = source.getAbsoluteLeft() - 500;
        int top = source.getAbsoluteTop() + 10;
        simplePopup.setPopupPosition(left, top);




      // Show the popup
      simplePopup.show();
      title.setFocus(true);
  }

  @UiHandler("deleteButton")
  void onDeleteClicked(ClickEvent event) {
	  if (Window.confirm("您确定要删除\"" + sessionObject.getTitle() + "\"此帖吗？") == true) {
		  forumService.removeSession(sessionObject.getId(), new AsyncCallback<Void>() {

			@Override
			public void onFailure(Throwable caught) {
				// TODO Auto-generated method stub

			}

			@Override
			public void onSuccess(Void result) {
				sessionUpdateHandler.onSessionUpdate(sessionObject);
			}

		  });
	  };
  }

  private void setVisibility(Widget widget, boolean visible) {
	    widget.getElement().getStyle().setVisibility(
	        visible ? Visibility.VISIBLE : Visibility.HIDDEN);
  }
}
